<template>
  <div class="question">
    <my-tabs :tab-list="tabList">
      <template v-slot="{ row }">
        <li
          class="item pointer"
          :class="{ active: status === row.type }"
          @click="handleClickMenu(row)"
        >
          {{ row.title }}
        </li>
      </template>
      <el-link slot="right" type="info" :underline="false" @click="handleReadAll">一键已读</el-link>
    </my-tabs>
    <div class="question-list" v-if="notifyQuestionList.length">
      <el-row
        class="question-item"
        type="flex"
        v-for="(item, index) in notifyQuestionList"
        :key="index"
      >
        <el-row type="flex" align="middle">
          <span class="badge" v-if="item.is_read == 0"></span>
          <edu-avatar
            shape="circle"
            :src="item.send_user_avatar_url"
            :size="40"
            @click="goUser(item.send_user_id)"
          ></edu-avatar>
        </el-row>
        <div class="content">
          <div class="name" @click="goUser(item.send_user_id)">
            {{ item.send_user_nick_name }} {{ item.notify_type_text }}
          </div>
          <div class="text">{{ item.content }}</div>
          <el-row type="flex" class="desc">
            <div class="time">
              {{ item.create_time | parseTime('{y}-{m}-{d} {h}:{i}') }}
            </div>
            <el-link :underline="false" @click="handleReply(item)">回复</el-link>
          </el-row>
        </div>
      </el-row>
    </div>
    <edu-no-data :image="false" text="暂时没有提问哦~" v-else></edu-no-data>
    <edu-pagination @handleCurrentChange="handleCurrentChange"></edu-pagination>

    <el-dialog
      title="提问"
      :visible.sync="replyVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      width="700px"
      top="15vh"
      @close="handleClose"
    >
      <div class="question-dialogue">
        <div class="question-dialogue_wrap" v-loading="questionLoading">
          <el-scrollbar ref="questionScrollbar">
            <div class="content">
              <template v-for="item in dialogueList">
                <!-- 我的回复 -->
                <el-row
                  type="flex"
                  justify="end"
                  class="item after"
                  :key="item.id"
                  v-if="item.user_id == accountInfo.id"
                >
                  <el-row type="flex" class="tool" align="bottom">
                    <div class="name" @click="goUser(item.user_id)">我</div>
                    <div class="text">{{ item.content }}</div>
                    <div v-if="item.attach_url.length > 0" class="preview">
                      <edu-image
                        v-for="(img, index) in item.attach_url"
                        :key="index"
                        :src="img"
                        :preview-src-list="item.attach_url"
                      ></edu-image>
                    </div>
                  </el-row>
                  <edu-avatar
                    shape="circle"
                    :src="item.avatar_url"
                    :size="40"
                    @click="goUser(item.user_id)"
                  ></edu-avatar>
                </el-row>
                <!-- 好友回复 -->
                <el-row type="flex" justify="start" class="item before" :key="item.id" v-else>
                  <edu-avatar
                    shape="circle"
                    :src="item.avatar_url"
                    :size="40"
                    @click="goUser(item.user_id)"
                  ></edu-avatar>
                  <el-row type="flex" class="tool">
                    <div class="name" @click="goUser(item.user_id)">{{ item.nick_name }}</div>
                    <div class="text">{{ item.content }}</div>
                    <div v-if="item.attach_url.length > 0" class="preview">
                      <edu-image
                        v-for="(img, index) in item.attach_url"
                        :key="index"
                        :src="img"
                        :preview-src-list="item.attach_url"
                      ></edu-image>
                    </div>
                  </el-row>
                </el-row>
              </template>
            </div>
          </el-scrollbar>
        </div>
        <div class="reply">
          <div class="question">
            <el-input
              type="textarea"
              size="mini"
              :minlength="1"
              :maxlength="200"
              v-model="replyContent"
              placeholder="请输入内容～"
            ></el-input>
            <edu-upload
              :args="argsMaterial"
              :value.sync="attachList"
              field="circle"
              ref="circleUpload"
            ></edu-upload>
          </div>
          <div class="foo">
            <el-button type="primary" size="mini" @click="handleReplySubmit">提问</el-button>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import MyTabs from '../components/myTab.vue'
import EduNoData from '@/components/EduNoData'
import EduPagination from '@/components/EduPagination'
import EduUpload from '@/components/EduUpload'
import debounce from '@/utils/debounce.js'
export default {
  components: {
    MyTabs,
    EduNoData,
    EduPagination,
    EduUpload
  },
  inject: ['reload'],
  data() {
    return {
      tabList: [
        {
          type: '2',
          title: '全部'
        },
        {
          type: '1',
          title: '已读'
        },
        {
          type: '0',
          title: '未读'
        }
      ],
      notifyQuestionList: [],
      replyVisible: false,
      questionLoading: false,
      questionForm: {},
      replyContent: '',
      dialogueList: [],
      status: '2',
      argsMaterial: {
        limit: 9,
        upload_type: 'pictureCard'
      },
      attachList: [],
      notifyData: {},
      notifyPageNum: 1,
      hasNext: false,
      scrollHeight: 0
    }
  },
  computed: {
    // 用户信息
    accountInfo() {
      return this.$store.getters['user/accountInfo']
    },
    questionState() {
      let state = false
      for (let item of this.notifyQuestionList) {
        if (item.is_read == 0) {
          state = true
        }
      }
      return state
    }
  },
  mounted() {
    this.handleNotifyQuestionInfo()
  },
  methods: {
    handleNotifyQuestionInfo() {
      this.$api.getNotifyQuestion(
        {
          status: this.status,
          page: this.$store.getters['paginate/page'],
          count: 20
        },
        res => {
          let data = res.data
          this.notifyQuestionList = data.data
          this.$store.dispatch('paginate/setPaginate', {
            listRows: 20,
            total: data.total
          })
        }
      )
    },
    // 分页
    handleCurrentChange() {
      this.handleNotifyQuestionInfo()
    },
    // 回复
    handleReply(item) {
      setTimeout(() => {
        this.questionLoading = true
      }, 200)
      this.replyVisible = !this.replyVisible
      this.questionForm = item
      this.notifyPageNum = 1
      this.handleQuestion(item)
      this.handleRead(item)
    },
    // 提交回复
    handleReplySubmit() {
      let query = {
        reply_user_id: this.questionForm.send_user_id,
        question_id: this.questionForm.notify_data_id,
        content: this.replyContent
      }
      if (!this.$util.isEmpty(this.attachList)) {
        query = {
          ...query,
          attach: String(this.attachList)
        }
      }
      this.$api.createQuestionReply(
        query,
        res => {
          this.$message.success(res.msg, res => {
            this.replyContent = ''
            this.attachList = []
            this.$refs['circleUpload'].clearFiles()
            this.notifyPageNum = 1
            this.handleQuestion(this.notifyData)
          })
        },
        error => {
          this.$message.error(error.msg)
        }
      )
    },
    // 读取信息
    handleRead(item) {
      if (item.is_read == 0) {
        this.$api.createMessageRead({
          operate: 1,
          object: 4,
          id: item.id
        })
      }
    },
    // 一键读取
    handleReadAll() {
      if (this.questionState) {
        this.$api.createMessageRead(
          {
            operate: 2,
            object: 4
          },
          res => {
            this.$message.success(res.msg, res => {
              this.handleNotifyQuestionInfo()
            })
          }
        )
      }
    },
    // 对话内容
    handleQuestion(item) {
      this.notifyData = item
      this.$api.getQuestion(
        item.notify_data_id,
        {
          page: this.notifyPageNum,
          count: 10
        },
        res => {
          const { data } = res
          let list = data.data
          if (list.length < 10) {
            this.hasNext = false
          } else {
            this.hasNext = true
          }
          if (this.notifyPageNum == 1) this.dialogueList = []
          this.dialogueList = list.concat(this.dialogueList)
          this.questionLoading = false
          let wrap = this.$refs['questionScrollbar'].$refs['wrap']
          // 对话消息置底
          this.$nextTick(() => {
            if (this.notifyPageNum == 1) {
              setTimeout(() => {
                wrap.scrollTop = wrap.scrollHeight
              }, 400)
            } else {
              if (wrap.scrollHeight > this.scrollHeight && list.length > 0) {
                wrap.scrollTop = wrap.scrollHeight - this.scrollHeight - 50
              }
            }
            this.scrollHeight = wrap.scrollHeight
          })
          wrap.addEventListener('scroll', this.handleScroll)
        }
      )
    },
    handleScroll(e) {
      const scrollTop = e.target.scrollTop
      if (scrollTop <= 0) {
        debounce(() => {
          if (this.hasNext) {
            this.notifyPageNum += 1
            this.handleQuestion(this.notifyData)
          }
        }, 1000)
      }
    },
    handleClose() {
      this.$refs['questionScrollbar'].$refs['wrap'].removeEventListener('scroll', this.handleScroll)
      this.dialogueList = []
      this.replyContent = ''
      this.attachList = []
      this.$refs['circleUpload'].clearFiles()
    },
    handleClickMenu(data) {
      this.status = data.type
      this.$store.dispatch('paginate/setPaginate', {
        currentPage: 1
      })
      this.handleNotifyQuestionInfo()
    },
    goUser(id) {
      this.$router.push({
        path: '/user',
        query: {
          id: id
        }
      })
    }
  },
  destroyed() {
    this.$store.commit('paginate/SET_PAGINATE_DEFAULT')
  }
}
</script>
<style lang="scss" scoped>
::v-deep .el-dialog {
  .el-dialog__header {
    border-bottom: 1px solid $border-color-divider;
    .el-dialog__title {
      font-size: 15px;
      color: $text-color-import;
    }
    .el-dialog__headerbtn .el-dialog__close {
      color: $text-color-secondary;
      font-size: 15px;
    }
  }
  .el-dialog__body {
    padding: 12px 22px;
  }
}
.question {
  .question-item {
    align-items: flex-start;
    padding: 15px 0;
    border-bottom: 1px solid $border-color-divider;
    .badge {
      margin-right: 8px;
      width: 8px;
      height: 8px;
      background: $color-danger;
      border-radius: 50%;
    }
    .content {
      flex: 1;
      margin-left: 12px;
      .name {
        font-size: 13px;
        color: $text-color-secondary;
        cursor: pointer;
      }
      .text {
        margin-top: 8px;
        font-size: 14px;
        line-height: 20px;
        font-weight: 600;
        color: $text-color-import;
      }
      .desc {
        margin-top: 13px;
        .time {
          margin-right: 30px;
          font-size: 12px;
          color: $text-color-secondary;
        }
        .el-link {
          font-size: 12px;
        }
      }
    }
  }
}
.question-dialogue {
  .question-dialogue_wrap {
    height: 340px;
    .el-scrollbar {
      height: 330px;
      ::v-deep .el-scrollbar__wrap {
        overflow-x: auto;
      }
    }
  }
  .item {
    & + .item {
      margin-top: 22px;
    }
    .tool {
      flex-direction: column;
    }
    &.before .tool {
      margin-left: 12px;
    }
    &.after .tool {
      margin-right: 12px;
    }
    .name {
      font-size: 12px;
      color: $text-color-secondary;
      cursor: pointer;
    }
    .text {
      max-width: 280px;
      margin-top: 8px;
      padding: 7px 12px;
      border-radius: 3px;
      font-size: 13px;
      line-height: 20px;
      letter-spacing: 1px;
    }
    .preview {
      display: flex;
      flex-direction: column;
      .el-image {
        margin-top: 8px;
        width: 125px;
      }
    }
    &.after .text {
      color: #fff;
      @include edu-color-primary(background-color);
    }
    &.before .text {
      color: $text-color-import;
      background-color: #f2f9ff;
    }
  }
  .reply {
    margin-top: 20px;
    .question {
      padding: 20px;
      border: 1px solid #e4e7ed;
      ::v-deep .el-textarea {
        .el-textarea__inner {
          padding: 0;
          border: none;
        }
      }
      ::v-deep .edu-form-upload {
        margin-top: 20px;
        max-width: 100%;
        .el-upload-list--picture-card .el-upload-list__item {
          width: 60px;
          height: 60px;
        }
        .el-upload--picture-card {
          width: 60px;
          height: 60px;
          line-height: 60px;
          border-radius: 0;
          .avatar-uploader-icon {
            font-size: 16px;
          }
        }
        .avatar-uploader-icon-text {
          font-size: 12px;
        }
      }
    }
    .foo {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }
}
</style>
